<?php
namespace frontend\controllers;

use Yii;
use common\models\LoginForm;
use frontend\models\SignupForm;

/**
 * Home controller
 */
class HomeController extends BaseController
{

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index', [
            'navid' => 'home',
        ]);
    }

    public function actionSearch()
    {
        return $this->render('index', [
            'navid' => 'search',
        ]);
    }

    public function actionDev()
    {
        return $this->render('index', [
            'navid' => 'dev@li',
        ]);
    }

    public function actionLogin() {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post(), '') && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionRegister() {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post(), '')) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        $model = new SignupForm();
        if($model->load(Yii::$app->request->post(), '')) {
            if($user == $model->signup()) {
                if(Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('register', [
            'model' => $model,
        ]);
    }

    public function actionLogout() {
        Yii::$app->user->logout();

        return $this->goHome();
    }

}
